import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Button, Image, CoverView } from '@tarojs/components';
import './index.scss'
import DataPicker from '@/components/DataPicker';
import { queryFundPoolNetExist, queryFundPoolNetIndex, queryFundPoolNetMetricsAndIndex } from '@/services/api/fund';
import { findMapsByFieldName } from '@/services/api/common';
import PdsTrendCharts from './charts';
import PdsEmpty from '@/components/common/pds_empty';
import { changeDecimalToPercentage } from '@/utils/fomatter';

interface FundDetailTreadProps {
    className?: string;
    fundId: String;
    menuOpenChange: Function;
    canFeedbackChange: Function;
}

class FundDetailTread extends Component<FundDetailTreadProps, any> {

    config = {
        navigationBarTitleText: '',
    }
    state = {
        yearButtonList: [{ label: '近1月', value: 30 }, { label: '近3月', value: 90 }, { label: '近6月', value: 180 }, { label: '近1年', value: 360 }, { label: '近3年', value: 1080 }],
        isMenuOpen: false,
        netValueList: [],
        indexValueList: [],
        metrics: {},
        isExistData: true,
        /// 1-可反馈，2-已反馈，3-无需反馈
        canFeedback: 3,
        index_type: {},
        queryNum: 30,
    }

    componentWillMount() {
        this.queryFundNetExist()
        const { queryNum } = this.state
        this.getFundNet(queryNum)
        var index_types: any[] = findMapsByFieldName('index_type')
        if (index_types.length > 0) {
            this.setState({
                index_type: index_types[0]
            }, () => {
                const { index_type } = this.state
                this.getFundPoolNetIndex(index_type['dictItemValue'], queryNum)
            })
        }
    }
    componentDidMount() { }
    componentWillReceiveProps(nextProps, nextContext) {


    }
    componentWillUnmount() { }

    /**
    * 查询近三年是否有净值
    * @returns 
    */
    queryFundNetExist() {
        if (this.props.fundId.length > 0) {
            queryFundPoolNetExist(this.props.fundId).then((resp) => {
                if (resp.code === 200) {
                    if(resp.data['canFeedback'] !== undefined){
                        const {canFeedbackChange } = this.props
                        canFeedbackChange(resp.data.canFeedback)
                    }
                    this.setState({ isExistData: resp.data['isExistData'], canFeedback: resp.data['canFeedback'] })
                }
            });
        }
    }

    /**
     * 请求最新净值
     * @param fundId 
     * @param queryNum 
     */
    getFundNet(queryNum) {
        if (this.props.fundId.length > 0) {
            queryFundPoolNetMetricsAndIndex(this.props.fundId, queryNum).then((resp) => {
                if(resp.code === 200){
                    if(resp.data['canFeedback'] !== undefined){
                        const {canFeedbackChange } = this.props
                        canFeedbackChange(resp.data.canFeedback)
                    }
                    this.setState({ netValueList: resp.data.data ?? [], metrics: resp.data.metrics,canFeedback:resp.data.canFeedback })
                }else{
                    this.setState({ netValueList:  [], metrics: {} })
                }
            });
        }
    }

    /**
     * 查询净值比对指数
     * @param queryNum 
     */
    getFundPoolNetIndex(index_type, query_num) {
        if (this.props.fundId.length > 0) {
            var fund_id: any = this.props.fundId;
            queryFundPoolNetIndex({ index_type, fund_id, query_num }).then((resp) => {
                if(resp.code === 200){
                    this.setState({ indexValueList: resp.data })
                }else{
                    this.setState({ indexValueList: [] })
                }
            });
        }
    }

    toggleMenu() {
        const { isMenuOpen } = this.state
        const { menuOpenChange } = this.props
        this.setState({
            isMenuOpen: !isMenuOpen
        })
        menuOpenChange(!isMenuOpen)
    }

    switchInexType(item) {
        this.setState({ index_type: item }, () => {
            const { index_type, queryNum } = this.state
            this.getFundPoolNetIndex(index_type['dictItemValue'], queryNum)
        })
    }

    changeCurrent(index) {
        const { index_type, yearButtonList, } = this.state
        var item = yearButtonList[index]
        this.setState({ queryNum: item['value'] }, () => {
            const { queryNum } = this.state
            this.getFundNet(queryNum)
            this.getFundPoolNetIndex(index_type['dictItemValue'], queryNum)
        })
    }


    getNetValueZdf() {
        const { netValueList, } = this.state
        var lastNetValue: any = null;
        const net_value_length = netValueList.length;
        if (net_value_length > 0) {
            // console.log(net_value_length)
            lastNetValue = netValueList[net_value_length - 1];
        }
        if (lastNetValue === null) {
            return '-'
        }
        if (Number(lastNetValue['preTotalNet']) === 0) {
            return "0.00%"
        }
        return ((Number(lastNetValue['totalNet']) - Number(lastNetValue['preTotalNet'])) / Number(lastNetValue['preTotalNet']) * 100).toFixed(2) + '%'
    }

    getNetValueClassName() {
        const { netValueList, } = this.state
        var lastNetValue: any = null;
        const net_value_length = netValueList.length;
        if (net_value_length > 0) {
            lastNetValue = netValueList[net_value_length - 1];
        }
        if (lastNetValue === null) {
            return ''
        }
        if (Number(lastNetValue['preTotalNet']) === 0) {
            return ''
        }
        return (Number(lastNetValue['totalNet']) - Number(lastNetValue['preTotalNet'])) > 0 ? 'num-positive-text' : 'num-negative-text'
    }

    getIndexZdf() {
        const { indexValueList, } = this.state
        var lastIndexValue: any = null;
        const index_value_length = indexValueList.length;
        if (index_value_length > 0) {
            lastIndexValue = indexValueList[index_value_length - 1];
        }
        if (index_value_length === 0) {
            return "0.00%"
        }
        if (lastIndexValue === null) {
            return '-'
        }
        if (index_value_length >= 2) {
            lastIndexValue = indexValueList[index_value_length - 1];
            return (((Number(lastIndexValue['indexValue']) - Number(indexValueList[0]['indexValue'])) / Number(indexValueList[0]['indexValue'])) * 100).toFixed(2) + '%'
        }

    }

    getInexZdfClassName() {
        const { indexValueList, } = this.state
        var lastIndexValue: any = null;
        const index_value_length = indexValueList.length;
        if (index_value_length > 0) {
            lastIndexValue = indexValueList[index_value_length - 1];
        }
        if (index_value_length === 0) {
            return ""
        }
        if (lastIndexValue === null) {
            return ''
        }
        if (index_value_length >= 2) {
            lastIndexValue = indexValueList[index_value_length - 1];
            return Number(lastIndexValue['indexValue']) - Number(indexValueList[0]['indexValue']) > 0 ? 'num-positive-text' : 'num-negative-text'
        }
    }

    getMaximumRetraction() {
        const { metrics } = this.state
        if (metrics === undefined || metrics['maximumRetraction'] === undefined || metrics['maximumRetraction'] === null) {
            return '-'
        }
        return changeDecimalToPercentage(metrics['maximumRetraction'], 2) + '%'
    }


    render() {
        const { className } = this.props
        const { yearButtonList, isMenuOpen, netValueList, indexValueList, isExistData, index_type, metrics } = this.state

        var index_types: any[] = findMapsByFieldName('index_type')

        return (
            <View className={`fund-detail-tread ${className}`}>
                <View className='fund-detail-tread-header'>
                    <View className='fund-detail-tread-header-item'>
                        <View className='fund-detail-tread-header-item-icon product'></View>
                        <View className='fund-detail-tread-header-item-context '>
                            <View className=''>本产品</View>
                            <View className={this.getNetValueClassName()}>{this.getNetValueZdf()}</View>
                        </View>
                    </View>

                    <View className='fund-detail-tread-header-item'>
                        <View className='fund-detail-tread-header-item-icon withdrawal'>
                            <Image src={require('@/assets/icons/mine/fund_detail_withdrawal.svg')}></Image>
                        </View>
                        <View className='fund-detail-tread-header-item-context'>
                            <View className=''>最大回撤</View>
                            <View className={Number(metrics['maximumRetraction']) > 0 ? '.num-positive-text' : (Number(metrics['maximumRetraction']) < 0 ? 'num-negative-text' : '')}>{`${Number(metrics['maximumRetraction']) > 0 ? '+' : ''}`}{this.getMaximumRetraction()}</View>
                        </View>

                    </View>
                    <View className="menu-container">
                        <View className='fund-detail-tread-header-item index' onClick={this.toggleMenu.bind(this)}>
                            <View className='fund-detail-tread-header-item-icon index'>

                            </View>
                            <View className='fund-detail-tread-header-item-context'>
                                <View className=''>{index_type['dictItemName']}</View>
                                <View className={this.getInexZdfClassName()}>{this.getIndexZdf()}</View>
                            </View>
                            <View className='fund-detail-tread-header-item-icon index-right'>
                                <Image src={require('@/assets/icons/public/public_arrow_bottom.svg')}></Image>
                            </View>
                            {isMenuOpen && (
                                <>
                                    <CoverView className="menu-overlay" onClick={this.toggleMenu.bind(this)} ></CoverView>
                                    <CoverView className="menu-options">
                                        {
                                            index_types.map((item, index) => {
                                                return <CoverView className={`menu-options-item ${item['dictItemName'] === index_type['dictItemName'] ? 'menu-options-item-active' : ''}`} onClick={(e) => this.switchInexType(item)}>{item['dictItemName']}</CoverView>
                                            })
                                        }
                                    </CoverView>
                                </>

                            )}
                        </View>
                    </View>

                </View>

                <View className='charts'>
                    {
                        isExistData ?
                            <>
                                {
                                    <PdsTrendCharts netValue={netValueList} indexValue={indexValueList} indexName={index_type['dictItemName']} chartHidden={isMenuOpen}></PdsTrendCharts>
                                }
                            </>
                            :
                            <PdsEmpty placeholderText='暂无业绩走势'></PdsEmpty>
                    }

                </View>
                <View className='bottom-year'>
                    <DataPicker changeCurrent={(e) => this.changeCurrent(e)} dataList={yearButtonList}></DataPicker>
                </View>

            </View>
        );
    }
}

export default FundDetailTread;